package net.begincode.common.email;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

public class EmailSenderImpl implements EmailSender {
    private Logger LOGGER = LoggerFactory.getLogger(EmailSenderImpl.class);
    private JavaMailSenderImpl javaMailSender;
    private MimeMessageHelper mimeMessageHelper;
    private MimeMessage mimeMessage;

    public EmailSenderImpl(EmailConfig emailConfig) {
        javaMailSender = new JavaMailSenderImpl();
        // 设置邮件服务器
        javaMailSender.setHost(emailConfig.getHost());
        //设置用户名密码
        javaMailSender.setUsername(emailConfig.getUserName());
        javaMailSender.setPassword(emailConfig.getPassword());
        javaMailSender.setDefaultEncoding("UTF-8");
        //属性信息
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");  // 验证用户名和密码
        properties.put("mail.smtp.timeout", "25000");
        properties.put("mail.smtp.port", "25");
        javaMailSender.setJavaMailProperties(properties);
        mimeMessage = javaMailSender.createMimeMessage();
        mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        try {
            mimeMessageHelper.setFrom(emailConfig.getFromEmail(), emailConfig.getNickName() == null ? emailConfig.getFromEmail() : emailConfig.getNickName());
        } catch (MessagingException e) {
            LOGGER.error("EmailSenderImpl.MessagingException", e);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("EmailSenderImpl.UnsupportedEncodingException", e);
        }
    }

    @Override
    public boolean sendEmail(String emailTo, String subject, String text) throws
            MessagingException {
        return sendEmail(emailTo, subject, text, false);
    }

    @Override
    public boolean sendEmail4Html(String emailTo, String subject, String text) throws
            MessagingException {
        return sendEmail(emailTo, subject, text, true);
    }

    private boolean sendEmail(String emailTo, String subject, String text, boolean isHtml) throws
            MessagingException {
        mimeMessageHelper.setTo(emailTo);
        mimeMessageHelper.setSubject(subject);
        if (isHtml) {
            mimeMessageHelper.setText(text, true);
        } else {
            mimeMessageHelper.setText(text);
        }
        javaMailSender.send(mimeMessage);
        return true;
    }
}
